package com.puman.beautyfarmcounselor.ui.task;

import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.puman.beautyfarmcounselor.IndexActivity;
import com.puman.beautyfarmcounselor.MainActivity;
import com.puman.beautyfarmcounselor.R;
import com.puman.beautyfarmcounselor.http.AjaxCallBack;
import com.puman.beautyfarmcounselor.ui.home.model.Advertising;
import com.puman.beautyfarmcounselor.ui.task.adpter.TaskListViewAdapter;
import com.puman.beautyfarmcounselor.ui.task.model.TaskItem;
import com.puman.beautyfarmcounselor.ui.task.model.TaskItemList;
import com.puman.beautyfarmcounselor.util.MethedUtil;
import com.puman.beautyfarmcounselor.util.XTHttp;
import com.puman.beautyfarmcounselor.util.config.GlobalData;
import com.puman.beautyfarmcounselor.util.config.RequestAddr;
import com.puman.beautyfarmcounselor.util.view.MultiSwipeRefreshLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * A placeholder fragment containing a simple view.
 */
@EFragment(R.layout.task_main)
public class TaskFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, com.puman.beautyfarmcounselor.util.view.SwipeRefreshLayout.OnLoadListener {
    /**
     * init variable
     */
    private int mImageViewArray[] = {R.drawable.task_item1, R.drawable.task_item2, R.drawable.task_item3,
            R.drawable.task_item4, R.drawable.task_item4};

    private String mItemName[] = {"新会员邀约", "新品上市邀约", "常规客情维护", "促销活动通知", "促销活动通知"};

    private TaskListViewAdapter taskListViewAdapter;

    protected LayoutManagerType mCurrentLayoutManagerType;

    @Override
    public void onLoad() {
        loadFinish();
    }


    @UiThread(delay = 2000)
    void loadFinish() {
        swipeRefreshLayout.setLoading(false);
    }


    private enum LayoutManagerType {
        GRID_LAYOUT_MANAGER,
        LINEAR_LAYOUT_MANAGER
    }

    private static final String KEY_LAYOUT_MANAGER = "layoutManager";

    private static final int SPAN_COUNT = 2;

    protected RecyclerView.LayoutManager mLayoutManager;

    public TaskItemList taskItemList;
    /**
     * init UI
     */
    @ViewById(R.id.base_title)
    TextView topTitle;
    @ViewById(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @ViewById(R.id.multswiperefresh)
    MultiSwipeRefreshLayout mSwipeRefreshLayout;
    @ViewById(R.id.swiperefresh)
    com.puman.beautyfarmcounselor.util.view.SwipeRefreshLayout swipeRefreshLayout;

    public TaskFragment() {

    }


    @AfterViews
    void updateView() {
        topTitle.setText("任务");
//        initData();
        initView();
        getData();
    }

    private void initData() {
//        int lengh = mImageViewArray.length;
//        taskItemList.clear();
//        for (int i = 0; i < lengh; i++) {
//            TaskItem taskItem = new TaskItem();
//            taskItem.setImageSrc(mImageViewArray[i]);
//            taskItem.setTitle(mItemName[i]);
////            taskItem.setPersontage((25 + i * 35)%100 + "");
////            taskItem.setProportion("12/35");
//            if (i == 0) {
//                taskItem.setTip("nihao wo shi tip nihao wo shi tipnihao wo shi tipnihao wo shi tipnihao wo shi tip");
//            } else {
//                taskItem.setTip("");
//            }
//            taskItemList.add(taskItem);
//        }
    }

    private void initView() {

        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

        setRecyclerViewLayoutManager(mCurrentLayoutManagerType);


        //设置子布局
        mSwipeRefreshLayout.setSwipeableChildren(R.id.swiperefresh);
        //设置监听
        mSwipeRefreshLayout.setOnRefreshListener(this);

        swipeRefreshLayout.setOnLoadListener(this);
        swipeRefreshLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
//        swipeRefreshLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        swipeRefreshLayout.setLoadNoFull(false);
    }

    private void getData() {
        XTHttp xtHttp = new XTHttp();
        String url = "";
        url = RequestAddr.taskList + "emp_id=" + GlobalData.counselor.getData().getEmployee_id();
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                getSucFlag(o);

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }


    /**
     * 判断数据是否映射成功
     *
     * @param object http获取对象
     * @return true 映射成功  false 映射失败
     */
    private boolean getSucFlag(Object object) {
//        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper objectMapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            taskItemList = objectMapper.readValue(object.toString(), TaskItemList.class);
            taskListViewAdapter = new TaskListViewAdapter(this, taskItemList,mImageViewArray);
            mRecyclerView.setAdapter(taskListViewAdapter);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        if (taskItemList.isFlag()) {
            taskListViewAdapter.notifyDataSetChanged();
            return true;
        } else {
            return false;
        }
    }


    /**
     * Set RecyclerView's LayoutManager to the one given.
     *
     * @param layoutManagerType Type of layout manager to switch to.
     */
    public void setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) {
        int scrollPosition = 0;

        // If a layout manager has already been set, get current scroll position.
        if (mRecyclerView.getLayoutManager() != null) {
            scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
                    .findFirstCompletelyVisibleItemPosition();
        }

        switch (layoutManagerType) {
            case GRID_LAYOUT_MANAGER:
                mLayoutManager = new GridLayoutManager(getActivity(), SPAN_COUNT);
                mCurrentLayoutManagerType = LayoutManagerType.GRID_LAYOUT_MANAGER;
                break;
            case LINEAR_LAYOUT_MANAGER:
                mLayoutManager = new LinearLayoutManager(getActivity());
                mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
                break;
            default:
                mLayoutManager = new LinearLayoutManager(getActivity());
                mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
        }

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.scrollToPosition(scrollPosition);
    }

    @Override
    public void onRefresh() {
        if (!mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
        initiateRefresh();
    }

    @UiThread(delay = 3000)
    void initiateRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
    }

//    @ItemClick
//    public void myListItemClicked(int position) {
//        Toast.makeText(MainActivity.getInstace(), ""+position, Toast.LENGTH_SHORT).show();
//    }

}
